import { useState, useEffect, useRef } from 'react'
import './App.css'
import Dashboard from './components/Dashboard'

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [currentUser, setCurrentUser] = useState(null)
  const [userType, setUserType] = useState('') // 'volunteer' | 'visually-impaired'
  const [showRoleChooser, setShowRoleChooser] = useState(false)
  const [showViRegister, setShowViRegister] = useState(false)
  const [showVolunteerRegister, setShowVolunteerRegister] = useState(false)
  const [isListening, setIsListening] = useState(false)
  const [transcript, setTranscript] = useState('')
  const [speechSupported, setSpeechSupported] = useState(false)
  const recognitionRef = useRef(null)

  useEffect(() => {
    const savedUser = localStorage.getItem('currentUser')
    const savedUserType = localStorage.getItem('userType')
    if (savedUser && savedUserType) {
      try {
        const userData = JSON.parse(savedUser)
        setCurrentUser(userData)
        setUserType(savedUserType)
        setIsLoggedIn(true)
      } catch (error) {
        localStorage.removeItem('currentUser')
        localStorage.removeItem('userType')
      }
    }
  }, [])

  // 检查浏览器是否支持语音识别
  useEffect(() => {
    const isSupported = 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window
    setSpeechSupported(isSupported)
  }, [])

  // 初始化语音识别
  const initSpeechRecognition = () => {
    if (!speechSupported) {
      alert('您的浏览器不支持语音识别功能')
      return false
    }

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    const recog = new SpeechRecognition()
    recog.continuous = true
    recog.interimResults = false
    recog.lang = 'zh-CN'

    recog.onstart = () => {
      setIsListening(true)
      console.log('语音识别已开始')
    }
    
    recog.onend = () => {
      setIsListening(false)
      console.log('语音识别已结束')
    }
    
    recog.onerror = (event) => {
      setIsListening(false)
      console.error('语音识别错误:', event.error)
      
      if (event.error === 'not-allowed') {
        alert('请允许浏览器使用麦克风权限')
      } else if (event.error === 'audio-capture') {
        alert('无法访问麦克风，请检查设备连接')
      }
    }
    
    recog.onresult = (event) => {
      const text = event.results[event.results.length - 1][0].transcript || ''
      setTranscript(text)
      console.log('识别结果:', text)
      
      const normalized = text.replace(/\s/g, '')
      if (normalized.includes('注册')) {
        setShowViRegister(true)
        recog.stop()
      }
    }

    recognitionRef.current = recog
    return true
  }

  // 开始语音识别
  const startListening = () => {
    if (!recognitionRef.current) {
      if (!initSpeechRecognition()) return
    }
    
    try {
      recognitionRef.current.start()
    } catch (error) {
      console.error('启动语音识别失败:', error)
      alert('启动语音识别失败，请重试')
    }
  }

  // 停止语音识别
  const stopListening = () => {
    if (recognitionRef.current && isListening) {
      try {
        recognitionRef.current.stop()
      } catch (error) {
        console.error('停止语音识别失败:', error)
      }
    }
  }

  const tryWebAuthn = async () => {
    if (!('PublicKeyCredential' in window)) {
      throw new Error('此设备/浏览器不支持指纹登录')
    }
    // 说明：演示环境下没有后端下发的挑战与凭证信息。
    // 这里仅做可用性探测，并不创建真实的凭证请求。
    // 如需接入真实指纹登录，请在后端实现 WebAuthn 注册与登录流程。
    return true
  }

  const handleFingerprintLogin = async (type) => {
    try {
      await tryWebAuthn()
      // 若传入了类型（来自身份选择），直接创建并登录
      if (type) {
        createAndLoginUser(type)
        return
      }
      // 未传入类型：表示用户点击全屏指纹区
      // 检查是否已有注册信息
      const savedUser = localStorage.getItem('currentUser')
      const savedUserType = localStorage.getItem('userType')
      if (savedUser && savedUserType) {
        try {
          const userData = JSON.parse(savedUser)
          setCurrentUser(userData)
          setUserType(savedUserType)
          setIsLoggedIn(true)
          return
        } catch {}
      }
      // 未注册：弹出身份选择
      setShowRoleChooser(true)
    } catch (e) {
      alert(e.message || '指纹登录失败，请重试')
    }
  }

  const createAndLoginUser = (type) => {
    const now = Date.now()
    if (type === 'volunteer') {
      const newUser = {
        id: now,
        name: '志愿者用户',
        phone: '',
        email: '',
        avatar: '🧑‍💼',
        rating: 0,
        serviceCount: 0,
        monthlyServiceCount: 0,
        onTimeRate: '0%'
      }
      setCurrentUser(newUser)
      setUserType('volunteer')
      setIsLoggedIn(true)
      localStorage.setItem('currentUser', JSON.stringify(newUser))
      localStorage.setItem('userType', 'volunteer')
      setShowRoleChooser(false)
    } else {
      const newUser = {
        id: now,
        name: '视障用户',
        phone: '',
        email: '',
        avatar: '👁️',
        helpCount: 0,
        lastHelpTime: null,
        averageRating: 0,
        averageResponseTime: '0分钟',
        satisfactionRate: '0%'
      }
      setCurrentUser(newUser)
      setUserType('visually-impaired')
      setIsLoggedIn(true)
      localStorage.setItem('currentUser', JSON.stringify(newUser))
      localStorage.setItem('userType', 'visually-impaired')
      setShowRoleChooser(false)
    }
  }

  const handleLogout = () => {
    setIsLoggedIn(false)
    setCurrentUser(null)
    setUserType('')
    localStorage.removeItem('currentUser')
    localStorage.removeItem('userType')
    alert('已退出登录')
  }

  if (isLoggedIn) {
    return (
      <Dashboard 
        currentUser={currentUser} 
        userType={userType} 
        onLogout={handleLogout} 
      />
    )
  }

  return (
    <div className="app" role="main">
      <div className="background-elements">
        <div className="floating-heart">❤️</div>
        <div className="floating-eye">👁️</div>
        <div className="floating-hands">🤝</div>
        <div className="floating-star">⭐</div>
      </div>

      {/* 全屏指纹识别区域 */}
      <button
        className="fingerprint-fullscreen"
        onClick={() => handleFingerprintLogin()}
        aria-label="点击进行指纹识别登录"
      >
        <div className="fingerprint-content">
          <div className="fingerprint-icon">🔒</div>
          <div className="fingerprint-title">指纹识别登录</div>
          <div className="fingerprint-subtitle">点击屏幕任意位置开始识别</div>
          {('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) && (
            <div style={{ marginTop: 16, color: '#7f8c8d', fontSize: '0.95rem' }}>
              {isListening ? '🎤 正在语音监听：说“注册”进入视障人士注册页' : '🎤 语音不可用'}
              {transcript && (
                <div style={{ marginTop: 6 }}>识别结果：{transcript}</div>
              )}
            </div>
          )}
        </div>
      </button>

      {/* 志愿者注册按钮（需点击） */}
      <button
        type="button"
        className="btn btn-primary"
        onClick={() => setShowVolunteerRegister(true)}
        style={{ position: 'fixed', top: 20, right: 20, zIndex: 3 }}
        aria-label="志愿者注册"
      >
        🧑‍💼 志愿者注册
      </button>

      {/* 身份选择弹层（仅在首次未注册时出现） */}
      {showRoleChooser && (
        <div className="role-chooser-overlay" role="dialog" aria-modal="true">
          <div className="role-chooser">
            <h2 className="form-title" style={{ textAlign: 'center', marginBottom: 15 }}>选择您的身份以完成注册</h2>
            <div className="button-group">
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => handleFingerprintLogin('volunteer')}
              >
                🧑‍💼 我是志愿者
              </button>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={() => handleFingerprintLogin('visually-impaired')}
              >
                👁️ 我是视障人士
              </button>
            </div>
            <p className="subtitle" style={{ textAlign: 'center', marginTop: 12 }}>
              首次注册后，后续触摸屏幕即可通过指纹直接进入对应系统。
            </p>
          </div>
        </div>
      )}

      {/* 视障人士注册页（语音“注册”触发） */}
      {showViRegister && (
        <div className="role-chooser-overlay" role="dialog" aria-modal="true">
          <div className="role-chooser">
            <h2 className="form-title" style={{ textAlign: 'center', marginBottom: 15 }}>视障人士注册</h2>
            <div className="button-group" style={{ marginTop: 10 }}>
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => handleFingerprintLogin('visually-impaired')}
              >
                👁️ 使用指纹完成注册并进入系统
              </button>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={() => setShowViRegister(false)}
              >
                取消
              </button>
            </div>
            <p className="subtitle" style={{ textAlign: 'center', marginTop: 12 }}>
              语音入口：在首页说“注册”即可打开此页面。
            </p>
          </div>
        </div>
      )}

      {/* 志愿者注册页（需点击按钮进入） */}
      {showVolunteerRegister && (
        <div className="role-chooser-overlay" role="dialog" aria-modal="true">
          <div className="role-chooser">
            <h2 className="form-title" style={{ textAlign: 'center', marginBottom: 15 }}>志愿者注册</h2>
            <div
              className="fingerprint-enroll-area"
              tabIndex={0}
              role="button"
              aria-label="点击此区域进行指纹注册"
              onClick={() => createAndLoginUser('volunteer')}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') createAndLoginUser('volunteer') }}
            >
              <div className="fingerprint-enroll-content">
                <div className="fingerprint-enroll-icon">🫳🔒</div>
                <div className="fingerprint-enroll-title">点击此区域进行指纹注册</div>
                <div className="fingerprint-enroll-subtitle">将手指放置传感器以完成验证</div>
              </div>
            </div>
            <div className="button-group" style={{ marginTop: 14 }}>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={() => setShowVolunteerRegister(false)}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default App